<?php
/**
 * 基础异常
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/5/28
 * Time: 15:57
 * Mail: hjklrchang@qq.com
 */

namespace app\base\exception;

use think\Config;
use think\Exception;
use Throwable;
class BaseException extends Exception
{
    // HTTP 状态吗
    public $httpCode = 400;
    // 异常信息
    public $msg = "接口错误";
    // 自定义错误码
    public $errorCode = 0;

    public function __construct($message = "", $code = 0, Throwable $previous = null)
    {
        //parent::__construct($message, $code, $previous);
        if( empty($message) ){
            return;
        }
        if( is_string($message) ){
            $this->msg = $message;
            return;
        }
        // 异常信息传入数字时解析错误内容
        if( is_numeric($message) ){
            Config::set(include APP_PATH . '/../config/api/config.php', 'api');
            $errMsgArr = Config::get('api.error_msg');
            $msg = isset($errMsgArr[$message]) ? $errMsgArr[$message] : '错误类型未定义';
            $this->msg = $msg;
            return;
        }
        // 异常信息传入为数组
        if( is_array($message) ){
            if( array_key_exists('httpCode', $message) ){
                $this->httpCode = $message['httpCode'];
            }
            if( array_key_exists('msg', $message) ){
                // 如果为数组，拼接成字符串
                if(is_array($message['msg'])) {
                    $msgStr = '';
                    foreach ($message['msg'] as $key => $value){
                        $msgStr .= "{$key}：{$value}；";
                    }
                    $this->msg = $msgStr;
                }else {
                    $this->msg = $message['msg'];
                }

            }
            if( array_key_exists('errorCode', $message) ){
                $this->errorCode = $message['errorCode'];
            }
            return;
        }
    }
}
